<?php
/**
 * CheckBill.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-22
 * Time: 8:49
 */

namespace App\Http\Controllers\Api\Finance;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\Tables;

class CheckBill extends Base
{
    public function payAll()
    {
        $id = (int) $this->request->post('bid');
        $oid = (array) $this->request->post('oid');
        if($id <= 0) { return $this->responseFail('无信息');}
        $oid = array_filter($oid);
        if(empty($oid)) { return $this->responseFail('无操作订单'); }
        $customer = Tables\Customer::find($id);
        if(empty($customer)) {
            return $this->responseFail('找不到客户信息');
        }

        $orderList = Tables\Order::query()->where('customer_id', $customer['id'])
            ->where('dumped', Tables\Order::No_Dumped)
            ->where('pay_status', '!=',Tables\Order::Pay_status_Ok)
            ->whereIn('id', $oid)
            ->get();
        \DB::beginTransaction();
        try {
            $addTime = time();
            $totalMoney = 0;
            foreach($orderList as $order) {
                $debt = (double) $order['real_price'] - (double) $order['paid_price'];
                $totalMoney += $debt;
                $order['paid_price'] = $order['real_price'];
                $order['pay_status'] = Tables\Order::Pay_status_Ok;
                if(!(bool)$order->save()) { throw new RunException('操作失败(1)');}
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => '批量消账',
                    'oid'  => $order['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('操作失败(2)'); }
                $ok = (bool) Tables\OrderPay::insert([
                    'oid' => $order['id'],
                    'aid' => 0,
                    'a_name' => '批量消账',
                    'money' => $debt,
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('操作失败(2)'); }
            }
            $ok = (bool) Tables\CashFlow::insert([
                'change' => $totalMoney,
                'desc'   => '批量消账 客户：'.$customer['name'],
                'type'   => Tables\CashFlow::TYPE_Income_Order,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('操作失败(3)'); }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }
}